package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jthinking.common.util.ip.IPInfo;
import com.jthinking.common.util.ip.IPInfoUtils;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.PlatformCCourse;
import com.ruoyi.teaching.domain.PlatformPComment;
import com.ruoyi.teaching.domain.PlatformUVirtual;
import com.ruoyi.teaching.domain.UniversalCreateUpdate;
import com.ruoyi.teaching.mapper.PlatformCCourseMapper;
import com.ruoyi.teaching.mapper.PlatformPCommentMapper;
import com.ruoyi.teaching.mapper.PlatformUVirtualMapper;
import com.ruoyi.teaching.service.PlatformPCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2024-07-01
 */
@Service
public class PlatformPCommentServiceImpl extends ServiceImpl<PlatformPCommentMapper, PlatformPComment> implements PlatformPCommentService {
    @Autowired
    private PlatformPCommentMapper platformPCommentMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private PlatformCCourseMapper platformCCourseMapper;

    @Autowired
    private PlatformUVirtualMapper platformUVirtualMapper;


    @Override
    public AjaxResult selectPlatformPCommentList(Integer pageNum, Integer pageSize, Integer commentType, Integer commentProjectId) {
        Page<PlatformPComment> platformPCommentPage = new Page<>(pageNum, pageSize);
        QueryWrapper<PlatformPComment> platformPCommentQueryWrapper = new QueryWrapper<>();
        platformPCommentQueryWrapper.eq("comment_type", commentType).eq("comment_project_id", commentProjectId);
        Page<PlatformPComment> platformPCommentPage1 = platformPCommentMapper.selectPage(platformPCommentPage, platformPCommentQueryWrapper);
        return new AjaxResult(HttpStatus.SUCCESS,"查询成功", platformPCommentPage1);
    }

    /**
     * 插入评论并更新对应项目的评分
     *
     * @param platformPComment 评论对象
     * @return AjaxResult 结果对象
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult insertPlatformPComment(PlatformPComment platformPComment) {
        // 获取创建者信息并设置到评论对象中
        UniversalCreateUpdate create = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformPComment.setCreateBy(create.getName());
        platformPComment.setCreateTime(DateUtils.getNowDate());
        platformPComment.setCreateId(create.getId());
        platformPComment.setCommentNickName(create.getName());
        SysUser user = sysUserMapper.selectUserById(create.getId().longValue());
        platformPComment.setAvatar(user.getAvatar());
        platformPComment.setCommentPersonId(create.getId().longValue());
        // 获取评论地点
        String ip = IpUtils.getIpAddr();
        IPInfo address = IPInfoUtils.getIpInfo(ip);
        if (StringUtils.isNotEmpty(address.getProvince()) && !address.getProvince().equals("未知")) {
            platformPComment.setCommentProvince(address.getProvince());
        } else {
            String realAddressByIP = AddressUtils.getRealAddressByIP(ip);
            if (!realAddressByIP.startsWith("XX") && !realAddressByIP.equals("内网IP")) {
                String[] parts = realAddressByIP.split(" ");
                if (parts.length > 0) {
                    // 取第一个有效部分作为省份
                    platformPComment.setCommentProvince(parts[0].trim());
                }
            }else {
                platformPComment.setCommentProvince("未知地区");
            }
        }

        // 插入评论
        int insert = platformPCommentMapper.insert(platformPComment);
        if (insert > 0) {
            // 计算并更新对应项目的评分
            updateProjectGrade(platformPComment);
            return new AjaxResult(HttpStatus.SUCCESS, "评论成功");
        }
        throw new RuntimeException("评论失败");
    }

    /**
     * 更新对应项目的评分
     *
     * @param platformPComment 评论对象
     */
    private void updateProjectGrade(PlatformPComment platformPComment) {
        BigDecimal gradeSum = new BigDecimal(0);
        int commentCount;

        // 查询条件封装器
        QueryWrapper<PlatformPComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("comment_type", platformPComment.getCommentType())
                .eq("comment_project_id", platformPComment.getCommentProjectId());

        // 获取所有评论
        List<PlatformPComment> platformPComments = platformPCommentMapper.selectList(queryWrapper);
        commentCount = platformPComments.size();

        // 计算评分总和
        for (PlatformPComment comment : platformPComments) {
            gradeSum = gradeSum.add(BigDecimal.valueOf(comment.getGrade()));
        }

        // 计算平均评分
        BigDecimal avgGrade = gradeSum.divide(BigDecimal.valueOf(commentCount), 1, RoundingMode.HALF_UP);

        // 更新对应项目的评分
        if (platformPComment.getCommentType() == 0) {
            // 更新备课授课的评分
            PlatformCCourse platformCCourse = new PlatformCCourse();
            platformCCourse.setId(platformPComment.getCommentProjectId().intValue());
            platformCCourse.setGrade(avgGrade.doubleValue());
            platformCCourseMapper.updateById(platformCCourse);
        } else if (platformPComment.getCommentType() == 1) {
            // 更新虚拟仿真的评分
            PlatformUVirtual platformUVirtual = new PlatformUVirtual();
            platformUVirtual.setId(platformPComment.getCommentProjectId());
            platformUVirtual.setGrade(avgGrade.doubleValue());
            platformUVirtualMapper.updateById(platformUVirtual);
        }
    }



    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult updatePlatformPComment(PlatformPComment platformPComment) {
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(sysUserMapper);
        platformPComment.setUpdateBy(update.getName());
        platformPComment.setUpdateTime(DateUtils.getNowDate());
        platformPComment.setUpdateId(update.getId());
        int updateResult = platformPCommentMapper.updateById(platformPComment);
        if (updateResult > 0) {
            return new AjaxResult(HttpStatus.SUCCESS, "更新成功");
        }
        throw new RuntimeException("更新失败");
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deletePlatformPCommentByIds(Long[] ids) {
        int length = ids.length;
        int deleteCount = platformPCommentMapper.deleteBatchIds(Arrays.asList(ids));
        if (length == deleteCount) {
            return new AjaxResult(HttpStatus.SUCCESS, "删除成功");
        }
        throw new RuntimeException("删除失败");
    }
}
